package netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class EventLoopServer {
  public static void main(String[] args) {
    DefaultEventLoopGroup group = new DefaultEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
      @Override
      protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline().addLast(group,"handler1",new ChannelInboundHandlerAdapter(){
          @Override
          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            log.debug(buf.toString(Charset.defaultCharset()));
            ctx.fireChannelRead(msg);
          }
        });
        ch.pipeline().addLast("handler2",new ChannelInboundHandlerAdapter(){
          @Override
          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            log.debug(buf.toString(Charset.defaultCharset()));
            ctx.fireChannelRead(msg);
          }
        });
        ch.pipeline().addLast(group,"handler3",new ChannelInboundHandlerAdapter(){
          @Override
          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            log.debug(buf.toString(Charset.defaultCharset()));
          }
        });
      }
    });
    bootstrap.bind(8080);
  }
}
